(function () {
    function focusPrev(pool) {
        var a = document.activeElement;
        if (!a || pool.index(a) === -1) {
            pool.first().focus();
            return;
        }
        var currIdx = pool.index(a);
        if (currIdx > 0)
            pool.eq(currIdx - 1).focus();
        else
            pool.last().focus();
    }
    function focusNext(pool) {
        var a = document.activeElement;
        if (!a || pool.index(a) === -1) {
            pool.first().focus();
            return;
        }
        var currIdx = pool.index(a);
//console.log(currIdx);
//console.log(pool.length - 1);
        if (currIdx < pool.length - 1)
            pool.eq(currIdx + 1).focus();
        else
            pool.first().focus();
    }
    var INPUT_SELECTOR = "input,select,textarea,button,a", IGNORE_CSS = "e2t-ignore";
    jQuery.fn.getFocusCandidates = function (tabRange) {
        return this.find(INPUT_SELECTOR)
                .filter("[tabindex]:not([tabindex=-1])")
                .filter(":not([disabled]):not([readonly]):visible" + (tabRange ? "" : ":not(." + IGNORE_CSS + ")"))
                .sort(function (a, b) {
                    return a.tabIndex > b.tabIndex ? 1 : -1;
                });
    };
    var CONTAINER_CSS = "e2t-container", ACTIVE_CSS = "e2t-active";
    jQuery.fn.enableEnterToTab = function (options) {
        var settings = $.extend({
            captureTabKey: false,
            enter2Tab: true
        }, options);
        return this.each(function () {
            var $container = $(this);
            $container.addClass(CONTAINER_CSS).on("keydown", "[tabindex]:not(textarea)", function (e) {
                var isTab = e.which === 9;
                var isRevTab = isTab && e.shiftKey;
                var isEnter = e.which === 13;
                var $fld = $(this);
//    console.log($fld);
                var isIgnore = $fld.is(".e2t-ignore"), isKeyOff = $fld.is(".e2t-keyoff"), isBtn = $fld.is(":button");
                if (enter2Tab && (isEnter && (isIgnore || isKeyOff || isBtn))) 
                    return;
                if (enter2Tab === false && (isEnter || (isIgnore || isKeyOff)))
                    return;
                if (isEnter || (settings.captureTabKey && isTab)) {
                    e.preventDefault();
                    if (isRevTab)
                        focusPrev($container.getFocusCandidates(isTab));
                    else
                        focusNext($container.getFocusCandidates(isTab));
                }
            });
        });
    };
})(jQuery);